<?php

	$starttime = '07:00';

	if (isset($_POST['add-submit'])) {
		$return = isset($_SESSION['return_path']) ? $_SESSION['return_path'] : $path.$table;
		$redirect = true;

		switch($table) {
			case 'bookings':
				//$_POST['services'] = implode(',', $_POST['services']);
				$arr = explode(',', $_POST['timeblock']);
				unset($_POST['timeblock']);
				$time = '';
				$mins = 0;
				for ($i=0; $i<sizeof($arr); $i++) {
					if ($arr[$i] == 1) {
						if ($time == '') $time = date('H:i:s', strtotime($starttime.' + '.($i*30).' minutes'));
						$mins += 30;
					}
				}
				$_POST['start'] = $_POST['date'].' '.$time;
				$_POST['end'] = date('Y-m-d H:i:s', strtotime($_POST['start'].' + '.$mins.' minutes'));
				unset($_POST['date']);
				// let's double check if there is already a booking:
				$newStart = $_POST['start'];
				$newEnd = $_POST['end'];
				$query = "SELECT * FROM bookings WHERE start BETWEEN $newStart AND $newEnd OR end BETWEEN $newStart AND $newEnd OR $newStart BETWEEN start AND end AND spaceid=".$_POST['spaceid'];
				$res = $cn->Data($query, false);
				if (sizeof($res) > 0) {
					$redirect = false;
					echo '<h2>Error making booking</h2>';
					echo '<p>Most likely someone made a booking for the same time while you were entering your details.<br/>Please try again using the button on the top right.</p>';
				} else
					$result = $cn->Add($table, $_POST, false, array('add-submit'));
				break;
			
			case 'companies':
			case 'users':
				$tbl = $table == 'companies' ? 'users' : $table;
				if ($tbl == 'users') $name = str_replace(' ', '', strtolower($_POST['name']));
				else $name = str_replace(' ', '', strtolower($_POST['company']));
				$_POST['accesscode'] = substr($name, 0, 4).rand(1000, 9999);
				$_POST['password'] = md5($_POST['password']);
				$_POST['verified'] = 1;
				$result = $cn->Add($tbl, $_POST, false, array('add-submit'));
				$id = $cn->LastID();
				$result = $cn->Add('settcredit', array('userid'=>$id, 'settcredit'=>0, 'freedays'=>0), false);
				break;

			/*case 'company_users':
				$name = str_replace(' ', '', strtolower($_POST['name']));
				$_POST['accesscode'] = substr($name, 0, 4).rand(1000, 9999);
				$result = $cn->Add($table, $_POST, false, array('add-submit'));
				break;*/
			
			default:
				$result = $cn->Add($table, $_POST, false, array('add-submit'));
		}

		if ($redirect) {
			$result = $cn->Add('logs', array('userid'=>$user_id, 'date'=>date('Y-m-d H:i:s'), 'description'=>'User ['.$userdata['name'].'] added ['.$table.'] result id ['.$cn->LastID().']', 'type'=>'add'), false);
			$cn->Close();
			header('location: '.$return);
		}		
			
	} else {

		$excl	 	= array('id'); 
		$labels		= array();
		$types		= array();
		$form 		= true;
		$now = date("Y-m-d H:i:s");

		switch($table) {

			// user

			case 'settcredit':
				// IF NO SUBSCRIPTION THEN WHAT?
				$redirect = true;
				$res = $cn->Data('select startdate, enddate, subscriptiontypeid from subscriptions where userid='.$user_id.' and paid=1', false);
				if (sizeof($res) > 0) {
					if ($res[0]['enddate'] == $res[0]['startdate'] || $res[0]['enddate'] > $now) {
						$redirect = false;
						$form = false;
						$res = $cn->Data('select dailyrate from subscription_types where id='.$res[0]['subscriptiontypeid'], false);
						$price = $res[0]['dailyrate'];
						echo "<form class=\"dark\" method=\"post\" action=\"$path$table/purchase\">\n";
						echo "<h3 class=\"noclear\">Purchase Sett Credit: <input type=\"text\" id=\"amount\" name=\"amount\" class=\"dynamic input-year\" value=\"1\" /> days</h3>\n";
						echo "<button class=\"add_new\" type=\"submit\" id=\"confirm-purchase\"><img src=\"".$path."img/blank.gif\" alt=\"\" /> Confirm Purchase</button>";
						echo "<p>Drag the slider to increase purchase amount</p>\n";
						echo "<ul class=\"progress slider\"><li data-percentage=\"1\"><!-- --></li><li class=\"scrubber\"><!-- --></li></ul>\n";
						echo "<ul class=\"details\"><li class=\"label\">Price Per Day:</li><li>R$price</li><li class=\"label\">Total Cost:</li><li class=\"total\">R$price</li></ul>\n";
						echo "<input type=\"hidden\" id=\"ppd\" name=\"ppd\" value=\"$price\" />\n";
						echo "</form>\n";
					}
				}
				if ($redirect) {
					$form = false;
					echo "<p>You don't have an active subscription. Please add a subscription <a href=\"".$path."subscription\">here</a></p>\n";
				}
			
				break;

			case 'bookings':
				/*if ($user_type == 0) {
					$labels = array('Space', 'Number of Occupants', '', '', 'Start Time', 'Duration (Hours)', 'Added Services');
					$types = array('tablelinkdropdown|spaces|id|label', 'integer', 'hidden|'.$user_id, 'hidden|'.$comp, 'date-time|'.date('Y-m-d H:i'), 'decimal', 'tablelinkmulti|services|id|label|blank');
				}*/
				$form = false;
				$str = '<form method="post" action="'.$path.$table.'/book" class="booking">';
				if ($user_type == 0) $str .= '<input type="hidden" name="userid" id="userid" value="'.$user_id.'" />';

				$str .= '<label for="">Select Building</label>';
				$str .= "<span class=\"select\">\n";
				$str .= "<input id=\"building\" type=\"hidden\" value=\"\" />\n";
				$str .= "<span>Select Building...</span>\n<ul>\n";
				$res = $cn->Data('select id, label from buildings order by label asc', false);
				foreach ($res as $row) $str .= "<li data-value=\"".$row['id']."\">".$row['label']."</li>\n";
				$str .= "</ul>\n</span>";

				$str .= '<label for="">Select Space</label>';
				$str .= "<span class=\"select disabled\" id=\"spaces\">\n";
				$str .= "<input id=\"spaceid\" type=\"hidden\" name=\"spaceid\" value=\"\" />\n";
				$str .= "<span>&nbsp;</span>\n<ul>\n";
				$str .= "</ul>\n</span>";

				$str .= '<label for="occupants">Occupants</label>';
				$str .= "<input id=\"occupants\" name=\"occupants\" type=\"text\" class=\"input-integer\" value=\"1\" disabled />";

				$str .= '<label for="date">Date and Time</label>';
				$str .= "<input id=\"date\" name=\"date\" type=\"text\" class=\"input-date\" value=\"".date('Y-m-d')."\" disabled />";

				$str .= '<label for="time">Booking</label>';
				$str .= '<ul class="time">';
				for ($i=0; $i<24; $i++) {
					$class = '';
					if ($i > 21) $class .= 'last';
					$str .= '<li data-index="'.$i.'" class="'.$class.'">'.date('H:i', strtotime($starttime.' + '.($i*30).' minutes')).'</li>';
				}
				$str .= '</ul>';
				$str .= '<input type="hidden" id="timeblock" name="timeblock" />';
				$str .= '<label>&nbsp;</label><h4 class="cost">TOTAL COST OF BOOKING: <span class="price">R0</span></h4>';
				$str .= '<button type="submit" name="add-submit">Add</button></form>';
				echo $str;
				break;

			case 'training_bookings':
				$form = false;
				echo '<input type="hidden" id="training-booking" value="1" />';
				array_push($excl, 'paid', 'invoice');
				$labels = array('Training Package', '', 'Date', 'Number of Delegates', 'Extra dietary requirements');
					$types = array('hidden|'.$user_id, 'tablelinkdropdown|training|id|label', 'datedisabled', '', 'textarea');
				echo $cn->AddForm($table, 'post', $path.$table.'/book', $excl, $labels, $types, false);
				break;

			// admin

			case 'subscription_types':
				array_push($excl, 'duration');
				$labels = array('Title', /*'Duration (days)',*/ 'Free Days', 'Daily Rate', 'Price');
				$types = array('', /*'integer',*/ 'integer', 'decimal', 'decimal');
				break;

			case 'users':
				array_push($excl, 'iscompany', 'linked', 'verified', 'validation', 'accesscode');
				$labels = array('Title', 'Name', 'Position', 'Company', 'Mobile', 'Email', 'Address', 'Province', 'LinkedIn URL', 'Facebook URL', 'Twitter URL', 'Password');
				$types = array('', '', '', '', 'telephone', '', '', 'dropdown|The Eastern Cape,The Free State,Gauteng,KwaZulu-Natal,Limpopo,Mpumalanga,The Northern Cape,North West,The Western Cape', '', '', '', 'password');
				break;

			case 'companies':
				/*array_push($excl, 'validation', 'verified', 'settcredit', 'validation', 'accesscode');
				$labels = array('Company Name', 'Account Manager Name', 'Account Manager Mobile', 'Account Manager Email', 'Company Address', 'Company Province', 'Admin Password', 'Account Verified', 'Access Code', 'Sett Credit');
				$types = array('', '', 'telephone', '', '', 'dropdown|The Eastern Cape,The Free State,Gauteng,KwaZulu-Natal,Limpopo,Mpumalanga,The Northern Cape,North West,The Western Cape', 'password');*/
				$table = 'users';
				array_push($excl, 'title', 'linked', 'verified', 'validation', 'accesscode');
				$labels = array('', 'Account Manager Name', 'Position', 'Company', 'Account Manager Mobile', 'Account Manager Email', 'Address', 'Province', 'LinkedIn URL', 'Facebook URL', 'Twitter URL', 'Password');
				$types = array('hidden|1', '', '', '', 'telephone', '', '', 'dropdown|The Eastern Cape,The Free State,Gauteng,KwaZulu-Natal,Limpopo,Mpumalanga,The Northern Cape,North West,The Western Cape', '', '', '', 'password');
				break;

			case 'buildings':
				$labels = array('Building Title', 'Manager', 'Telephone Number', 'Mobile Number', 'Email', 'Address', 'Province');
				$types = array('', '', 'telephone', 'telephone', '', '', 'dropdown|The Eastern Cape,The Free State,Gauteng,KwaZulu-Natal,Limpopo,Mpumalanga,The Northern Cape,North West,The Western Cape');
				break;

			case 'services':
				$labels = array('Title', 'Description', 'Cost', 'Cost is per person');
				$types = array('', 'textarea', 'decimal', 'checkbox');
				break;

			case 'training':
				$labels = array('Label', 'Description', 'Start Time', 'End Time', 'Minimum Capacity', 'Maximum Capacity', 'Price per delegate');
				$types = array('', 'textarea', 'time', 'time', 'integer', 'integer', 'decimal');
				break;

			// Children Tables

			case 'subscriptions':
				$excl = array('id', 'userid', 'iscompany', 'subscriptiontypeid', 'startdate');
				break;

			case 'company_users':
				$labels = array('', 'Name', 'Mobile Number', 'Email', 'Access Code');
				if ($post_id == null) $post_id = $user_id;
				$accesscode = $cn->Data('select accesscode from users where id='.$post_id, false);
				if (sizeof($accesscode) > 0) $accesscode = $accesscode[0]['accesscode'];
				else $accesscode = '';
				$types = array('hidden|'.$post_id, '', 'telephone', '', 'readonly|'.$accesscode);
				break;

			case 'spaces':
				$labels = array('', 'Label', 'Capacity', 'Min Booking Time', 'Max Booking Time', 'Hourly Rate');
				$types = array('hidden|'.$post_id, '', 'integer', 'decimal', 'decimal', 'decimal');
				break;
		}

		if ($form) echo $cn->AddForm($table, 'post', '', $excl, $labels, $types, false);

	}
?>